package com.csk.zsk.compents.action;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.safehaus.uuid.UUID;
import org.safehaus.uuid.UUIDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.csk.zsk.commons.action.AjaxActionSupport;
import com.csk.zsk.commons.utils.web.struts2.Struts2Utils;
import com.csk.zsk.compents.entity.Message;
import com.csk.zsk.compents.entity.Playlist;
import com.csk.zsk.compents.entity.User;
import com.csk.zsk.compents.entity.VisitQuantity;
import com.csk.zsk.compents.service.MessageService;
import com.csk.zsk.compents.service.PlaylistService;
import com.csk.zsk.compents.service.UserService;
import com.csk.zsk.compents.service.VisitQuantityService;
import com.csk.zsk.compents.utils.Constants;

/**
 * @author helin
 * 
 */
@Controller
@Scope("prototype")
public class AccountAction extends AjaxActionSupport {

	private static final long serialVersionUID = 4897857402098076265L;

	@Autowired
	private UserService userService;
	@Autowired
	private VisitQuantityService visitQuantityService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private PlaylistService playlistService;

	private String id;
	private String loginName;
	private String pwd;
	private String slidePwd;
	private String realName;
	private String sex;
	private Date birthdate;
	private String mobile;
	private String email;
	private String address;
	private String cardOrder;
	private String wallPaper;
	private File photo;
	private String photoFileName;

	private String title;
	private String content;

	public String toLogin() {
		return "toLogin";
	}

	/**
	 * 登陆
	 */
	public void login() {
		String msg = "";
		boolean flag = true;
		try {
			HttpSession session = Struts2Utils.getSession();
			User user = userService.findUserByLoginName(loginName);
			if (user != null) {
				if (pwd.equals("") && slidePwd.equals("")) {
					msg = "请检查用户名和密码";
					flag = false;

				} else {
					if (!pwd.equals("")) {
						if (!user.getPwd().equals(pwd)) {
							msg = "请检查用户名和密码";
							flag = false;

						}
					} else if (!slidePwd.equals("")) {
						if (!user.getSlidePwd().equals(slidePwd)) {
							msg = "请检查用户名和密码";
							flag = false;
						}
					}
					if (flag) {
						msg = "success";
						session.setAttribute(Constants.USER_SESSION, user);
						VisitQuantity visitQuantity = new VisitQuantity();
						String ip = getIpAddress(Struts2Utils.getRequest());
						visitQuantity.setIp(ip);
						visitQuantity.setTime(new Date());
						visitQuantityService.saveVisitQuantity(visitQuantity);
					}
				}
			} else {
				msg = "请检查用户名和密码";
			}

		} catch (Exception e) {
			msg = "系统出现异常,请联系管理员";
		}
		Struts2Utils.renderText(msg);
	}

	/**
	 * 登出
	 */
	public String logout() {
		Struts2Utils.getSession().removeAttribute(Constants.USER_SESSION);
		return "toLogin";
	}

	/**
	 * 注册
	 */
	public void regist() {
		try {
			User user = new User();
			user.setLoginName(loginName);
			user.setPwd(pwd);
			user.setSlidePwd(slidePwd);
			userService.saveUser(user);

			Playlist playlist1 = new Playlist();
			playlist1.setName("我的乐库");
			playlist1.setIsSys(true);
			playlist1.setImageUrl("images/lib.jpg");
			playlist1.setUserId(user.getId());
			playlist1.setCreateTime(new Date());
			playlistService.savePlaylist(playlist1);

			Playlist playlist2 = new Playlist();
			playlist2.setName("我的最爱");
			playlist2.setIsSys(true);
			playlist2.setImageUrl("images/love.jpg");
			playlist2.setUserId(user.getId());
			playlist2.setCreateTime(new Date());
			playlistService.savePlaylist(playlist2);

			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 保存排序
	 */
	public void saveOrder() {
		try {
			User user = userService.getUser(id);
			user.setCardOrder(cardOrder);
			userService.saveUser(user);
			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 获取用户信息
	 */
	public void getUser() {
		User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
		user = userService.getUser(user.getId());
		Struts2Utils.renderJson(user);
	}

	/**
	 * 修改基本信息
	 */
	public void editInfo() {
		try {
			User user = userService.getUser(id);
			user.setRealName(realName);
			user.setSex(sex);
			user.setBirthdate(birthdate);
			user.setMobile(mobile);
			user.setEmail(email);
			user.setAddress(address);
			userService.saveUser(user);
			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 修改密码
	 */
	public void editPwd() {
		try {
			User user = userService.getUser(id);
			user.setPwd(pwd);
			userService.saveUser(user);
			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 修改头像
	 */
	@SuppressWarnings("deprecation")
	public void editPhoto() {
		try {
			User user = userService.getUser(id);
			if (user.getPhoto() != null && !"".equals(user.getPhoto())) {
				File f = new File(Struts2Utils.getRequest().getRealPath("") + File.separator
						+ user.getPhoto().replace("/", File.separator));
				if (f.exists()) {
					f.delete();
				}
			}
			String photoPath = "photo";
			photoPath += File.separator + id;
			File file = new File(Struts2Utils.getRequest().getRealPath("") + File.separator + photoPath, photoFileName);
			FileUtils.copyFile(photo, file);
			photoPath = photoPath + File.separator + photoFileName;
			user.setPhoto(photoPath.replace(File.separator, "/"));
			userService.saveUser(user);
			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 切割头像
	 */
	@SuppressWarnings("deprecation")
	public void drawPhoto() {
		try {
			User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
			user = userService.getUser(user.getId());
			Integer x = Integer.parseInt(Struts2Utils.getParameter("x"));
			Integer y = Integer.parseInt(Struts2Utils.getParameter("y"));
			Integer w = Integer.parseInt(Struts2Utils.getParameter("w"));
			Integer h = Integer.parseInt(Struts2Utils.getParameter("h"));
			if (user.getPhoto() != null && !"".equals(user.getPhoto())) {
				File f = new File(Struts2Utils.getRequest().getRealPath("") + File.separator
						+ user.getPhoto().replace("/", File.separator));

				BufferedImage src = ImageIO.read(f);
				ImageFilter filter = new CropImageFilter(x, y, w, h);
				Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(src.getSource(), filter));
				BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制小图
				g.dispose();
				// 输出为文件
				String photoPath = "photo" + File.separator + user.getId() + File.separator + "cut_img.jpg";
				String dir = Struts2Utils.getRequest().getRealPath("") + File.separator + photoPath;
				File f1 = new File(dir);
				ImageIO.write(tag, "JPEG", f1);

				if (f.exists()) {
					f.delete();
				}
				user.setPhoto(photoPath);
				userService.saveUser(user);
				Struts2Utils.renderText("success");
			}

		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 更新壁纸
	 */
	public void editWallPaper() {
		try {
			User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
			user = userService.getUser(user.getId());
			user.setWallPaper(wallPaper);
			userService.saveUser(user);
			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	/**
	 * 保存留言
	 */
	public void saveMessage() {
		try {
			User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
			Message message = new Message();
			message.setTitle(title);
			message.setContent(content);
			message.setUser(new User());
			message.getUser().setId(user.getId());
			messageService.saveMessage(message);
			Struts2Utils.renderText("success");
		} catch (Exception e) {
			Struts2Utils.renderText("fail");
		}
	}

	public String getIpAddress(HttpServletRequest request) throws Exception {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public String generateFileName() {
		UUIDGenerator generator = UUIDGenerator.getInstance();
		UUID uuid = generator.generateRandomBasedUUID();
		return uuid.toString();
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setSlidePwd(String slidePwd) {
		this.slidePwd = slidePwd;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public void setBirthdate(Date birthdate) {
		this.birthdate = birthdate;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public void setCardOrder(String cardOrder) {
		this.cardOrder = cardOrder;
	}

	public void setWallPaper(String wallPaper) {
		this.wallPaper = wallPaper;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setContent(String content) {
		this.content = content;
	}

}
